package com.zsr.example.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsr.example.config.listener.SubjectExcelListener;
import com.zsr.example.dto.excel.SubjectData;
import com.zsr.example.entity.EduSubject;
import com.zsr.example.mapper.EduSubjectMapper;
import com.zsr.example.service.EduSubjectService;
import com.zsr.example.vo.SubjectNestedVo;
import com.zsr.example.vo.SubjectVo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author zsr
 * @since 2021-11-13
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    /**
     * 添加课程分类
     * @param file
     * @param subjectService
     */
    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<SubjectNestedVo> getAllSubject() {
        return getAllSubject(null);
    }

    @Override
    public List<SubjectNestedVo> getAllSubject(Long count) {
        List<EduSubject> all = this.list(null);//所有分类
        List<EduSubject> eduSubjects1;
        if(count==null){
            eduSubjects1=all.stream().filter(i -> i.getParentId().equals("0")).collect(Collectors.toList());
        }else{
            eduSubjects1=all.stream().filter(i -> i.getParentId().equals("0")).limit(count).collect(Collectors.toList());
        }
        //二级分类
        List<EduSubject> eduSubjects2 =
                all.stream().filter(i -> !i.getParentId().equals("0")).collect(Collectors.toList());;//二级分类


        return eduSubjects1.stream().map(//一级分类重写map为OneSubject,
                a -> new SubjectNestedVo(a.getId(), a.getTitle(),//OneSubject中的List从eduSubjects2中筛选
                        eduSubjects2.stream().filter(b -> b.getParentId().equals(a.getId()))//filter ParentId等于一级分类的id
                                .map(c -> new SubjectVo(c.getId(), c.getTitle()))//二级分类重写map为TwoSubject
                                .collect(Collectors.toList())))
                .collect(Collectors.toList());
    }
}
